package com.sky.loveshop.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.sky.loveshop.entity.MqttClientEntity;
import com.sky.loveshop.entity.MqttTopic;
import com.sky.loveshop.service.MqttClientService;
import com.sky.loveshop.service.MqttTopicService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author xcy
 * @version V1.0
 * @description MQTT客户端创建
 * @date 2024/9/6 21:29
 */
@Component
@Slf4j
public class MqttClientCreate {
    @Resource
    private MqttClientManager mqttClientManager;
    //@Resource
    //private MqttConfig mqttConfig;
    @Resource
    private MqttClientService mqttClientService;
    @Resource
    private MqttTopicService mqttTopicService;

    /**
     * 创建MQTT客户端
     */
    @PostConstruct
    public void createMqttClient() {
        // 根据当前环境获取所有的客户端
        // 这里应该是只获取消息发布的客户，也就是也仅仅是消息发布的客户端要注册，其他设备要订阅主题，
        // 其他设备的客户端应该是他所在的系统来注册和订阅主题

        List<MqttClientEntity> clientList = mqttClientService.listAllByEnv();
        if (CollectionUtil.isEmpty(clientList)) {
            log.info("createMqttClientFail because client is empty");
            return;
        }

        for (MqttClientEntity c : clientList) {
            // 根据客户端id查询订阅的主题
            List<MqttTopic> mqttTopicList = mqttTopicService.getTopicsByClientId(c.getId());
            String topicPath = "";
            // 如果一个客户端订阅了多个主题，则将主题用"-"拼接起来
            if (CollectionUtil.isNotEmpty(mqttTopicList) && mqttTopicList.size() > 1) {
                String manyTopicPath = mqttTopicList.stream().map(MqttTopic::getTopicPath).collect(Collectors.joining("-"));
                topicPath = manyTopicPath;
            } else if (CollectionUtil.isNotEmpty(mqttTopicList) && mqttTopicList.size() == 1) {
                topicPath = mqttTopicList.get(0).getTopicPath();
            }
            // 创建客户端 有一点疑问，如果没有订阅主题的客户端也会创建客户端吗: 实际测试结果 -> 会
            mqttClientManager.createMqttClient(c.getClientId(), topicPath, c.getUserName(), c.getPassWord());
        }
    }
}